// src/stores/auth.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  // 从 localStorage 初始化状态
  const token = ref(localStorage.getItem('token') || '')
  const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)

  // Actions
  function setAuth(data) {
    token.value = data.token
    user.value = data.user
    
    // 同步到 localStorage
    localStorage.setItem('token', data.token)
    localStorage.setItem('user', JSON.stringify(data.user))
  }

  function clearAuth() {
    token.value = ''
    user.value = null
    
    // 清除 localStorage
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  return { 
    token, 
    user,
    isAuthenticated,
    setAuth,
    clearAuth
  }
})